package cn.slipi.core.component.loadbalance;

import cn.slipi.common.enums.LoadBalanceEnum;
import cn.slipi.common.rule.custom.entity.BalancePiece;
import cn.slipi.common.rule.custom.entity.LoadBalance;
import com.google.common.base.Preconditions;

/**
 * RoundRobinSelector
 */
public class RoundRobinSelector implements LoadBalanceSelector {

    private static Integer pos = 0;

    @Override
    public BalancePiece select(LoadBalance loadBalance, String ip) {
        Preconditions.checkNotNull(loadBalance);
        Preconditions.checkNotNull(loadBalance.getData());
        final BalancePiece[] balancePieces = loadBalance.getData();
        int length = balancePieces.length;
        BalancePiece balancePiece = null;
        synchronized (pos) {
            if (pos >= length) {
                pos = 0;
            }
            balancePiece = balancePieces[pos];
            pos++;
        }
        return balancePiece;

    }

    @Override
    public String getAlgorithm() {
        return LoadBalanceEnum.ROUND_ROBIN.getName();
    }
}
